import { fetchOptionsType, fetchDataType } from "./types";
const fetchOptions = {
  baseURL: "http://demonuxtapi.dishait.cn/pc",
  headers: {
    token:
      "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6bnVsbCwicGhvbmUiOiIxNTgqKioqOTI0MSIsImlkIjoyNTIsInVzZXJuYW1lIjoiY2VzaGkyMiIsIm5pY2tuYW1lIjoic3VtbWVyIiwicGFzc3dvcmQiOiI4ZDk2OWVlZjZlY2FkM2MyOWEzYTYyOTI4MGU2ODZjZjBjM2Y1ZDVhODZhZmYzY2ExMjAyMGM5MjNhZGM2YzkyIiwiYXZhdGFyIjoiaHR0cDovL2RlbW8tbXAzLm9zcy1jbi1zaGVuemhlbi5hbGl5dW5jcy5jb20vZWdnLWVkdS1kZW1vLzcyNGRlNTc0N2MyZDZkN2VjNzQ3LmpwZyIsIndlaXhpbl9vcGVuaWQiOm51bGwsInNleCI6IueUtyIsImRlc2MiOiIiLCJzdGF0dXMiOjEsImNyZWF0ZWRfdGltZSI6IjIwMjEtMDUtMTlUMTI6MjQ6NDguMDAwWiIsInVwZGF0ZWRfdGltZSI6IjIwMjEtMDUtMjNUMTA6NDA6NTcuMDAwWiIsImlhdCI6MTYyMjA0ODU0N30.vOIpiHM1v7X_k3VDXdtUwVA66a2f4dH0a-SnBr05ccU",
    appid: "bd9d01ecc75dbbaaefce",
  },
  initialCache: false,
  lazy: true,
};

function useFetchOptions(key: string, opt: Partial<fetchOptionsType> = {}) {
  opt.key = key;
  opt.headers = opt?.headers || fetchOptions.headers;
  opt.method = opt?.method || "GET";
  opt.initialCache = opt?.initialCache || fetchOptions.initialCache;
  opt.lazy = opt?.lazy || fetchOptions.lazy;
  if (opt.method == "POST") {
    opt.body = opt?.body;
  } else {
    delete opt.body;
  }
  return opt as object;
}

export function useQueryString(params: any = {}) {
  return Object.keys(params)
    .map((key) => {
      let val;
      if (typeof params[key] == "object") {
        val = JSON.stringify(params[key]);
      } else {
        val = params[key];
      }
      return `${key}=${encodeURIComponent(val)}`;
    })
    .join("&");
}

export const useGetHttp = async (
  key: string,
  url: string,
  params: object = {},
  options: Partial<fetchOptionsType> = {}
): Promise<fetchDataType> => {
  const option = useFetchOptions(key, { ...options, method: "GET" });
  const fetchUrl = `${fetchOptions.baseURL}${url}?${useQueryString(params)}`;
  console.log(fetchUrl);
  const { data, pending, error, refresh } = await useFetch(fetchUrl, {
    ...option,
    // transform: (t: any) => {
    //   return t?.obj;
    // },
  });
  return {
    data,
    pending,
    error,
    refresh,
  };
};

export const usePostHttp = async (
  key: string,
  url: string,
  params: object = {},
  options: Partial<fetchOptionsType> = {}
): Promise<fetchDataType> => {
  const option = useFetchOptions(key, { ...options, method: "POST" });
  console.log({
    ...option,
    body: params,
    // transform: (t: any) => {
    //   return t?.obj;
    // },
  });
  const { data, pending, error, refresh } = await useFetch(
    `${fetchOptions.baseURL}${url}`,
    {
      ...option,
      body: params,
      // transform: (t: any) => {
      //   return t?.obj;
      // },
    }
  );
  return {
    data,
    pending,
    error,
    refresh,
  };
};
